package com.person.monitor;

import static com.person.monitor.helper.VolumeHelper.COMMAND_CLOSE_VOLUME;
import static com.person.monitor.helper.VolumeHelper.COMMAND_OPEN_VOLUME;
import android.content.Context;
import android.media.AudioManager;
import android.text.TextUtils;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.person.monitor.helper.VolumeHelper;
import com.person.monitor.location.LocRet;
import java.util.List;

public class WorkVolumeProcess extends BaseProcess {

    private String keyValue = "Sky";

    private String proValue = "Pro_128141";

    private static LocRet workLoc = new LocRet(22.534516,113.947245,"work");//lat=22.53444,lng=113.94737 //22.534516,lng=113.947245

    private static final float WORK_RAD = 300f;

    AudioManager audioManager;

    public WorkVolumeProcess(Context context,String name){
        super(context,name);
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    }

    @Override
    public void processMonitor(List<MonitorInfo> list) {
        if(list.size() < 2 ) return;
        if(audioManager.isWiredHeadsetOn()) return;

        MonitorInfo last = list.get(1);
        MonitorInfo now = list.get(0);

        if(now.wifiContainKey(proValue)){
            if(!last.wifiContainKey(proValue)){
                openVolume();
            }
        }else if(now.wifiContainKey(keyValue)){
            closeVolume();
        }else if(calculateDistance(now.locRet) < WORK_RAD){
            closeVolume();
        }else if(calculateDistance(now.locRet) >= WORK_RAD && calculateDistance(last.locRet) < WORK_RAD ){
            openVolume();
        }
    }

    private void closeVolume(){
        int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        if(volume > 0) {
            VolumeHelper.getInstance().startActivityCommand(COMMAND_CLOSE_VOLUME);
        }
    }

    private void openVolume(){
        int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        if(volume <= 0) {
            VolumeHelper.getInstance().startActivityCommand(COMMAND_OPEN_VOLUME);
        }
    }

    public static float calculateDistance(LocRet locRet){
        if(locRet == null) return Long.MAX_VALUE;

        DPoint dPoint = new DPoint(workLoc.lat, workLoc.lng);
        DPoint lPoint = new DPoint(locRet.lat, locRet.lng);
        float distance = CoordinateConverter.calculateLineDistance(dPoint,lPoint);
        return distance;
    }

}
